package cn.wolfcode.shop.controller;

import cn.wolfcode.shop.exception.UserException;
import cn.wolfcode.shop.service.IUserLoginService;
import cn.wolfcode.shop.vo.JSONResultVo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by wolfcode on 2018/8/20.
 */
@RestController
@RequestMapping("/api/tokens")
public class LoginController {
    @Reference
    private IUserLoginService userLoginService;
    @PostMapping
    public JSONResultVo login(String username,String password){
        JSONResultVo vo = new JSONResultVo();
        try{
            String token = userLoginService.login(username,password);
            vo.setResult(token);
        }catch(UserException ex){
            ex.printStackTrace();
            vo.setErrorMsg(ex.getMessage());
        }
        return vo;
    }
    @DeleteMapping("/{tokens}")
    public JSONResultVo logout(@PathVariable("tokens") String token, HttpServletResponse response){
        JSONResultVo vo = new JSONResultVo();
        if(token==null || "".equals(token.trim())){
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            vo.setErrorMsg("参数有误,");
            return vo;
        }
        try{

            //执行删除操作
            userLoginService.logout(token);
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return vo;
        }catch(UserException ex){
            ex.printStackTrace();
            vo.setErrorMsg(ex.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return vo;
    }
}
